package com.sunny.core.filter;

import java.io.IOException;
import java.util.StringTokenizer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginFilter implements Filter {

	private String noFilterURLs = "";
	private String authAttribute;

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;

		Object user = request.getSession(true).getAttribute(authAttribute);
		if (user == null) {
			String contextPath = request.getContextPath();
			if (!contextPath.startsWith("/"))
				contextPath = "/" + contextPath;

			String requestURL = request.getRequestURI();
			String basePath = request.getScheme() + "://"
					+ request.getServerName() + ":" + request.getServerPort()
					+ contextPath + "/toLogin.jsp";
			if (isFilter(requestURL, contextPath)) {
				response.sendRedirect(basePath);
				return;
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		noFilterURLs = config.getInitParameter("noAuthURLs");
		authAttribute = config.getInitParameter("authAttr");
	}

	private boolean isFilter(String requestURL, String contextPath) {
		StringTokenizer st = new StringTokenizer(noFilterURLs, ";");
		while (st.hasMoreTokens()) {
			String url = contextPath + "/" + st.nextToken();
			if (requestURL.equals(url))
				return false;
		}
		return true;
	}

}
